package com.atguigu.medical.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.medical.realtime.app.BaseApp;
import com.atguigu.medical.realtime.bean.UserNewPatientBean;
import com.atguigu.medical.realtime.common.Constant;
import com.atguigu.medical.realtime.util.DateUtil;
import com.atguigu.medical.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @Author lzc
 * @Date 2023/4/28 14:47
 * 新增患者
 */
public class DwsUserNewPatientWindow extends BaseApp {
    public static void main(String[] args) {
        new DwsUserNewPatientWindow().init(
            40004,
            2,
            "DwsUserNewPatientWindow",
            Constant.TOPIC_DWD_DIAGNOSIS_CONSULTATION
        );
        
    }
    
    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        // 1. 把数据封装为 pojo 类型
        SingleOutputStreamOperator<UserNewPatientBean> beanStream = parseToPojo(stream);
        // 2. 开窗聚合
         SingleOutputStreamOperator<UserNewPatientBean> resultStream = windowAndAgg(beanStream);
        // 3. 写出到 clickhouse 中
          writeToClickHouse(resultStream);
        
        
    }
    
    private void writeToClickHouse(SingleOutputStreamOperator<UserNewPatientBean> resultStream) {
        resultStream.addSink(FlinkSinkUtil.getClickHouseSink("dws_user_new_patient_window", UserNewPatientBean.class));
    }
    
    private SingleOutputStreamOperator<UserNewPatientBean> windowAndAgg(
        SingleOutputStreamOperator<UserNewPatientBean> beanStream) {
        return beanStream
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<UserNewPatientBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((obj, ts) -> obj.getTs())
                    .withIdleness(Duration.ofSeconds(60))
            )
            .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
            .reduce(
                new ReduceFunction<UserNewPatientBean>() {
                    @Override
                    public UserNewPatientBean reduce(UserNewPatientBean value1,
                                                    UserNewPatientBean value2) throws Exception {
                        value1.setNewPatientCt(value1.getNewPatientCt() + value2.getNewPatientCt());
                        return value1;
                    }
                },
                new ProcessAllWindowFunction<UserNewPatientBean, UserNewPatientBean, TimeWindow>() {
                    @Override
                    public void process(Context ctx,
                                        Iterable<UserNewPatientBean> elements,
                                        Collector<UserNewPatientBean> out) throws Exception {
                        UserNewPatientBean bean = elements.iterator().next();
                        
                        bean.setStt(DateUtil.tsToDateTime(ctx.window().getStart()));
                        bean.setEdt(DateUtil.tsToDateTime(ctx.window().getEnd()));
                        bean.setTs(System.currentTimeMillis());
                        
                        out.collect(bean);
                    }
                }
            );
        
    }
    
    private SingleOutputStreamOperator<UserNewPatientBean> parseToPojo(DataStreamSource<String> stream) {
        return stream
            .map(JSON::parseObject)
            .keyBy(obj -> obj.getString("patient_id")) // 按照患者 id 分组
            .process(new KeyedProcessFunction<String, JSONObject, UserNewPatientBean>() {
                
                private ValueState<String> firstDiagnosisDateState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    firstDiagnosisDateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("firstDiagnosisDate", String.class));
                }
                
                @Override
                public void processElement(JSONObject value,
                                           Context ctx,
                                           Collector<UserNewPatientBean> out) throws Exception {
                    Long ts = value.getLong("ts");
                    String today = DateUtil.tsToDate(ts);
                    String firstDiagnosisDate = firstDiagnosisDateState.value();
                    if (firstDiagnosisDate == null) {  // 表是该患者首次问诊
                        
                        firstDiagnosisDateState.update(today);
                        // 输出数据
                        out.collect(new UserNewPatientBean("", "", 1L, ts));
                    }
                }
            });
        
    }
}
